//
//  AudioTool.m
//  2、SystemSound封装
//
//  Created by niit on 15/5/28.
//  Copyright (c) 2015年 niit. All rights reserved.
//

#import "AudioTool.h"

@implementation AudioTool

+(void)initialize{
//设置音频会话
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
}

+(SystemSoundID)playSystemSound:(NSString *)fileName{
    if (!fileName) {
        return 0;
    }
    SystemSoundID soundId;
    
    //加载url
    NSURL *fileUrl=[[NSBundle mainBundle]URLForResource:fileName withExtension:nil];
    if (!fileUrl) {
        return 0;
    }
    //创建系统音效
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileUrl, &soundId);
    //播放
    AudioServicesPlaySystemSound(soundId);
    return soundId;
}


//播放音乐
+(AVAudioPlayer *)playMusic:(NSString *)fileName{
    if (!fileName) {
        return nil;
    }
    AVAudioPlayer *player;
    NSURL *url=[[NSBundle mainBundle]URLForResource:fileName withExtension:nil];
    if (!url) {
        return nil;
    }
    player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    [player prepareToPlay];//准备播放，提前把这个音频文件放入缓存
    [player play];
    return player;
}


//根据url播放音乐
+(AVAudioPlayer *)playMusicWithUrl:(NSURL *)fileUrl{
    AVAudioPlayer *player;
    if (!fileUrl) {
        return nil;
    }
    player=[[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
    [player prepareToPlay];//准备播放，提前把这个音频文件放入缓存
    [player play];
    return player;
}

//录音
+(AVAudioRecorder *)startRecoder:(NSURL *)fileUrl{
    if (!fileUrl) {
        return nil;
    }
    //复制一下就行了 录制的设置
    NSMutableDictionary *settings = [NSMutableDictionary dictionary];
    [settings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM]
                forKey:AVFormatIDKey];//如果需要转码mp3需要用kAudioFormatLinearPCM
    [settings setValue:[NSNumber numberWithFloat:44100.0]
                forKey:AVSampleRateKey]; //采样率
    [settings setValue:[NSNumber numberWithInt:1]
                forKey:AVNumberOfChannelsKey];//通道的数目
    [settings setValue:[NSNumber numberWithInt:16]
                forKey:AVLinearPCMBitDepthKey];//采样位数  默认 16
    [settings setValue:[NSNumber numberWithBool:NO]
                forKey:AVLinearPCMIsBigEndianKey];//大端还是小端 是内存的组织方式
    [settings setValue:[NSNumber numberWithBool:NO]
                forKey:AVLinearPCMIsFloatKey];//采样信号是整数还是浮点数
    
    NSError *error;
    AVAudioRecorder *recoder=[[AVAudioRecorder alloc]initWithURL:fileUrl settings:settings error:&error];
    [recoder record];
    return recoder;
}

@end
